package com.amadeus.spin.devtool.soap.shooter.process;

import org.apache.log4j.Logger;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import com.amadeus.spin.devtool.soap.shooter.FatalException;
import com.amadeus.spin.devtool.soap.shooter.ProcessOutput;

/**
 * AddDelayToOutput is a simple class that makes a pause for the specified time.
 * AddDelayToOutput is called from the SOAP shooter.
 * 
 */
public class AddDelayToOutput implements ProcessOutput {

  private final static String XMLATTRIBUTE_VALUE = "value";

  private static Logger log = Logger.getLogger(AddDelayToOutput.class);

  /**
   * For the given xmlOutput string, process the config node
   */
  @Override
  public void processOutput(String xmlOutput, Node config, com.amadeus.spin.util.soapshooter.Shooter shooter)
      throws FatalException {
    // get delay value from config (ex <AddDelayToOutput value="500"/>)
    int delay = getDelayValue(config);
    log.info("Pausing for " + delay + " ms");
    try {
      Thread.sleep(delay);
    }
    catch (InterruptedException e) {
      String msg = "delay interruption";
      log.error(msg);
      throw new FatalException(msg);
    }
  }

  /**
   * Gets "value" attribute from "AddDelayToOutput" node.
   */
  private int getDelayValue(Node configNode) throws FatalException {
    NamedNodeMap attributes = configNode.getAttributes();
    Node value = attributes.getNamedItem(XMLATTRIBUTE_VALUE);
    if (value == null) {
      String msg = "delay node has incorrect format";
      log.error(msg);
      throw new FatalException(msg);
    }
    return (Integer.valueOf(value.getNodeValue()));
  }
}
